import pyecharts.options as opts
from pyecharts.charts import Bar, Pie
import pandas as pd
from collections import defaultdict

from get_data import get_data

# 调用get_data函数获取数据
data = get_data()

# 将数据转换为DataFrame
df = pd.DataFrame(data)

# 计算每个厂商的总销量
manufacturer_total_sales = df.groupby('manufacturer')['sales_volume'].sum().reset_index()
# 按销量排序并取前十
top_ten_manufacturers = manufacturer_total_sales.sort_values(
    by='sales_volume', ascending=False
).head(10)['manufacturer'].tolist()


# 从原始数据生成价格区间数据（仅包含前十厂商）
def generate_price_data():
    price_data = {"低价车": 0, "中价车": 0, "高价车": 0}

    # 过滤出前十厂商的数据
    filtered_df = df[df['manufacturer'].isin(top_ten_manufacturers)]

    for _, row in filtered_df.iterrows():
        try:
            price_range = row['price_range']
            if '-' in price_range:
                min_price, max_price = map(float, price_range.split('-'))
                avg_price = (min_price + max_price) / 2
            else:
                avg_price = float(price_range)

            sales_volume = row['sales_volume']
            if avg_price <= 15:
                price_data["低价车"] += sales_volume
            elif 15 < avg_price <= 25:
                price_data["中价车"] += sales_volume
            else:
                price_data["高价车"] += sales_volume
        except (ValueError, AttributeError):
            continue

    return price_data


# 获取包含柱形图和饼图的复合图表
def get_compound_chart() -> Bar:
    price_data = generate_price_data()

    # 准备柱形图数据（前十厂商的总销量）
    manufacturer_sales = {
        m: manufacturer_total_sales[manufacturer_total_sales['manufacturer'] == m]['sales_volume'].values[0]
        for m in top_ten_manufacturers
    }

    # 创建柱形图
    bar = (
        Bar()
        .add_xaxis(xaxis_data=top_ten_manufacturers)
        .add_yaxis(
            series_name="总销量",
            y_axis=[manufacturer_sales[m] for m in top_ten_manufacturers],
            label_opts=opts.LabelOpts(is_show=True, position="top"),
        )
        .set_global_opts(
            title_opts=opts.TitleOpts(
                title="销量前十厂商及价格区间分布",
                subtitle="数据来自销售记录"
            ),
            tooltip_opts=opts.TooltipOpts(
                is_show=True, trigger="axis", axis_pointer_type="shadow"
            ),
            legend_opts=opts.LegendOpts(pos_top="5%"),
            xaxis_opts=opts.AxisOpts(
                axislabel_opts=opts.LabelOpts(rotate=45, interval="auto")
            ),
        )
    )

    # 创建饼图
    pie = (
        Pie()
        .add(
            series_name="价格区间占比",
            data_pair=[
                ["低价车", price_data["低价车"]],
                ["中价车", price_data["中价车"]],
                ["高价车", price_data["高价车"]],
            ],
            center=["75%", "35%"],
            radius=["25%", "40%"],
        )
        .set_series_opts(
            tooltip_opts=opts.TooltipOpts(
                is_show=True,
                trigger="item",
                formatter="{a} <br/>{b}: {c} ({d}%)"
            ),
        )
    )

    return bar.overlap(pie)


# 生成复合图表
compound_chart = get_compound_chart()
compound_chart.render("top_manufacturer_analysis.html")